USE [VIETPUBLISHER]
GO

/****** Object:  UserDefinedFunction [dbo].[fn_GetOrderCode]    Script Date: 06/15/2012 06:50:25 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE   FUNCTION [dbo].[fn_GetOrderCode]()  
 RETURNS varchar(15)
 as  
begin
--check is null
declare @returnValue as varchar(15)
SELECT @returnValue=MAX(OrderCode) from T_BK_Order


SELECT @returnValue= 'INV' + CONVERT(VARCHAR(10), GETDATE(), 12) +'001' 

if(len(@returnValue) <> 0)
BEGIN

declare @pr_stt as varchar(3)
declare @pr_sttInt as int
SELECT @pr_sttInt = cast(RIGHT(MAX(OrderCode),  3) as int)  FROM T_BK_Order 

set @pr_sttInt =@pr_sttInt+1
SELECT @pr_stt=RIGHT('00'+ CONVERT(VARCHAR,@pr_sttInt),3) 


SELECT @returnValue='INV' + CONVERT(VARCHAR(10), GETDATE(), 12)+cast(@pr_stt as varchar(3))

END


return @returnValue
 	end
 	
 	
GO


